package com.atguigu.config;

import com.atguigu.service.UsersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


/**
 * @author mqx
 * @date 2020 年 7 月 20 日 0020 11:20:54
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UsersServiceImpl usersService;

    @Autowired
    private PersistentTokenRepository tokenRepository;
    // 注入PasswordEncoder 类到spring 容器中
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置认证
        http.formLogin()
                .loginPage("/index") // 配置哪个url为登录页面
                .loginProcessingUrl("/login") // 设置哪个是登录的url。
                //.successForwardUrl("/success") // 登录成功之后跳转到哪个url
                .defaultSuccessUrl("/success")
                .failureForwardUrl("/fail") // 登录失败之后跳转到哪个url
                .usernameParameter("loginAcct") // 获取登录用户名
                .passwordParameter("userPswd"); // 获取登录密码


        // 配置403 错误页面
        http.exceptionHandling().accessDeniedPage("/unauth");

        http.authorizeRequests()
                .antMatchers("/layui/**","/index") //表示配置请求路径
                .permitAll()
                .antMatchers("/findAll").hasRole("管理员")
                .antMatchers("/find").hasAnyAuthority("menu:system")
                .anyRequest()
                .authenticated(); //需要认证

        // 退出登录跳转到登录页面！
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/index").permitAll();

        // 开启记住我功能
        http.rememberMe()
                //.tokenValiditySeconds(10) // 单位是秒
                .tokenRepository(tokenRepository)
                .userDetailsService(usersService);
        // 关闭csrf
        // http.csrf().disable();

    }
}
